/**
 * Ext JS version 2
 *
 * @author      Tadasu Isogawa <isogawa@unoh.net>
 * @copyright   Copyright 2007-2008 Tadasu Isogawa
 * @license     GNU General Public License version 3
 *
 * The content of this file is an implementation of Ext JS version 2.
 * Thus this is subject to the Open Source License of Ext JS
 * http://extjs.com/license, and is licensed under GNU General Public
 * License version 3 http://www.gnu.org/copyleft/gpl.html
 */

Ext.BLANK_IMAGE_URL = 'ext/resources/images/default/s.gif';
var MobileSimulator = function() {
    var responseHeadersStore, historiesStore;
    var qrCodeDialog, authDialog;
    return {
        init: function() {
            Ext.QuickTips.init();
            //Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

            /**
             * Request Headers Panel
             */
            var headerRecord = Ext.data.Record.create([
                {name: 'name'},
                {name: 'value'}
            ]);
            var requestHeadersStore = new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({url: 'request-headers.php'}),
                reader: new Ext.data.JsonReader({root: 'headers'}, headerRecord)
            });
            requestHeadersStore.on('load', function() {
                if (Ext.getDom('url').value) {
                    Ext.getDom('request-form').submit();
                }
            });
            requestHeadersStore.load();
            var requestHeadersListStore = new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({url: 'request-headers-list.php'}),
                reader: new Ext.data.JsonReader({root: 'headersList'}, [
                    {name: 'id'},
                    {name: 'value'}
                ])
            });
            requestHeadersListStore.load();
            var requestHeadersListCombo = new Ext.form.ComboBox({
                store: requestHeadersListStore,
                forceSelection: true,
                displayField: 'value',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText: 'Select a setting...',
                selectOnFocus: true
            });
            requestHeadersListCombo.on('select', function(combo, record) {
                requestHeadersStore.load({params: {'id': record.data.id}});
            });
            var requestHeadersGrid = new Ext.grid.EditorGridPanel({
                applyTo: Ext.DomHelper.append(document.body, {
                    tag: 'div', id: 'request-headers'
                }),
                title: 'Request Headers',
                header: false,
                border: false,
                viewConfig: {
                    forceFit: true
                },
                store: requestHeadersStore,
                columns: [{
                    id: 'name',
                    header: 'Name',
                    dataIndex: 'name',
                    width: 150,
                    editor: new Ext.grid.GridEditor(new Ext.form.TextField({
                        allowBlank: false
                    }))
                },{
                    id: 'value',
                    header: 'Value',
                    dataIndex: 'value',
                    width: 450,
                    editor: new Ext.grid.GridEditor(new Ext.form.TextField({
                        allowBlank: false
                    }))
                }],
                tbar: [
                    requestHeadersListCombo,
                    {
                        text: 'Add an arbitrary header...',
                        icon: 'images-site/add.png',
                        cls: 'x-btn-text-icon',
                        tooltip: 'Leave the field blank if you don\'t want to send it',
                        handler: function() {
                            var r = new headerRecord({
                                name: 'New Header',
                                value: ''
                            });
                            requestHeadersGrid.stopEditing();
                            requestHeadersStore.insert(0, r);
                            requestHeadersGrid.startEditing(0, 0);
                        }
                    }
                ]
            });
            requestHeadersGrid.on('afteredit', function(e) {
                var ds = e.grid.getStore();
                var jsonString = '[';
                ds.each(function(record) {
                    jsonString += Ext.encode(record.data) + ',';
                });
                jsonString = jsonString.substring(0, jsonString.length -1) + ']';
                Ext.Ajax.request({
                    url: 'update-session.php', method: 'POST', params: {headers: jsonString}
                });
                //Ext.getDom('request-form').submit();
            });

            /**
             * Histories Panel
             */
            historiesStore = new Ext.data.GroupingStore({
                proxy: new Ext.data.HttpProxy({
                    url: 'histories.php'
                }),
                reader: new Ext.data.JsonReader({root: 'histories'}, [
                    'url', 'host', 'title',
                    {name: 'date', type: 'date', dateFormat: 'U'}
                ]),
                sortInfo: {field: 'date', direction: 'DESC'},
                groupField: 'host'
            });
            historiesStore.load();
            var historiesGrid = new Ext.grid.GridPanel({
                renderTo: Ext.DomHelper.append(document.body, {
                    tag: 'div', id: 'histories'
                }),
                title: 'Histories',
                header: false,
                border: false,
                view: new Ext.grid.GroupingView({
                    forceFit: true
                }),
                store: historiesStore,
                columns: [
                    {header: 'Title', width: 100, dataIndex: 'title', sortable: true},
                    {header: 'Address', width: 200, dataIndex: 'url', sortable: true},
                    {header: 'Last Visited', width: 50, dataIndex: 'date', sortable: true, renderer: Ext.util.Format.dateRenderer('H:i m/d')},
                    {header: 'Host', width: 50, dataIndex: 'host', sortable: true, hidden: true}
                ]
            });
            historiesGrid.on('rowdblclick', function(grid, rowIndex, e) {
                Ext.getDom('url').value = grid.getStore().getAt(rowIndex).data.url;
                Ext.getDom('request-form').submit();
            });

            /**
             * Response Headers Panel
             */
            responseHeadersStore = new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({
                    url: 'response-headers.php'
                }),
                reader: new Ext.data.JsonReader({root: 'headers'}, [
                    {name: 'name'},
                    {name: 'value'}
                ])
            });
            var responseHeadersGrid = new Ext.grid.GridPanel({
                renderTo: Ext.DomHelper.append(document.body, {
                    tag: 'div', id: 'response-headers'
                }),
                title: 'Response Headers',
                header: false,
                border: false,
                viewConfig: {
                    forceFit: true
                },
                store: responseHeadersStore,
                columns: [
                    {id: 'name',  header: 'Name',  dataIndex: 'name', width: 150},
                    {id: 'value', header: 'Value', dataIndex: 'value', width: 450}
                ]
            });

            /**
             * Proxy Frame
             */
            var proxyFrame = Ext.get(
                Ext.DomHelper.append(document.body, {
                    tag: 'iframe',
                    id: 'proxy-frame',
                    name: 'proxy-frame',
                    frameborder: '0',
                    style: 'width:100%;height:100%;margin:0;padding:0;border:0'
                })
            );
            proxyFrame.on('load', this.update.createDelegate(this));

            /**
             * Global Toolbar
             */
            var globalToolbar = new Ext.Toolbar(
                Ext.DomHelper.append(
                    Ext.DomHelper.append(
                        document.body,
                        {
                            tag: 'form',
                            id: 'request-form',
                            action: 'mobile-proxy.php',
                            method: 'get',
                            target: 'proxy-frame'
                        }
                    ),
                    {tag: 'div'}
                )
            );
            globalToolbar.add(new Ext.form.TextField({
                //emptyText: 'Enter an URL to get start...',
                id: 'url',
                name: 'url',
                width: 600
            }));
            globalToolbar.addButton({
                icon: 'images-site/resultset_next.png',
                cls:  'x-btn-icon',
                tooltip: 'Enter an URL to get start...',
                handler: function() {
                    Ext.getDom('request-form').submit();
                }
            });
            globalToolbar.addSeparator();
            globalToolbar.addButton({
                text: 'QR Code',
                icon: 'images-site/phone.png',
                cls: 'x-btn-text-icon',
                tooltip: 'Show QR code of the current URL',
                handler: this.showQrCode.createDelegate(this)
            });

            /**
             * Global Layout
             */
            new Ext.Viewport({
                layout: 'border',
                items: [
                    {
                        region: 'north',
                        contentEl: 'request-form',
                        height: 26,
                        autoScroll: false
                    },{
                        region: 'west',
                        contentEl: proxyFrame,
                        split: true,
                        width: 264,
                        collapsible: false,
                        autoScroll: false
                    },{
                        region: 'center',
                        layout: 'fit',
                        items: new Ext.TabPanel({
                            deferredRender: false,
                            activeTab: 4,
                            tabPosition: 'top',
                            items: [
                                responseHeadersGrid,
                                {
                                    contentEl: Ext.DomHelper.append(document.body, {
                                        tag: 'div', id: 'response-body'
                                    }),
                                    title: 'Response Body',
                                    header: false,
                                    autoScroll: true
                                },
                                historiesGrid,
                                requestHeadersGrid,
                                {
                                    contentEl: 'note',
                                    title: 'About',
                                    header: false,
                                    autoScroll: true,
                                    closable: true
                                }
                            ]
                        })
                    }
                 ]
            });

            /**
             * QR Code Dialog
             */
            qrCodeDialog = new Ext.Window({
                title: 'QR Code',
                modal: true,
                width: 240,
                height: 260,
                closeAction: 'hide',
                layout: 'fit',
                items: [new Ext.Panel({
                    contentEl: Ext.DomHelper.append(document.body, {
                        tag: 'div', id: 'qrcode'
                    })
                })],
                buttons: [{
                    text: 'Close',
                    handler: function() {
                        qrCodeDialog.hide();
                    }
                }],
                keys: [{
                    key: Ext.EventObject.ESC,
                    handler: function() {
                        qrCodeDialog.hide();
                    }
                }]
            });

            /**
             * Basic Authentication Dialog
             */
            var authForm = new Ext.FormPanel({
                renderTo: document.body,
                frame: true,
                labelWidth: 80,
                defaults: {width: 200},
                items: [
                    new Ext.form.Hidden({
                        id: 'auth-form-url',
                        name: '__post_params[action]'
                    }),
                    new Ext.form.Hidden({
                        id: 'auth-form-realm',
                        name: '__post_params[realm]'
                    }),
                    new Ext.form.TextField({
                        fieldLabel: 'Username',
                        name: '__post_params[username]',
                        allowBlank: false
                    }),
                    new Ext.form.TextField({
                        inputType: 'password',
                        fieldLabel: 'Password',
                        name: '__post_params[password]',
                        allowBlank: false
                    })
                ],
                onSubmit: Ext.emptyFn,
                buttons: [{
                    text: 'Submit',
                    handler: function() {
                        authDialog.hide();
                        authForm.getForm().getEl().dom.submit();
                    }
                },{
                    text: 'Cancel',
                    handler: function() {
                        authDialog.hide();
                    }
                }],
                keys: [{
                    key: Ext.EventObject.ENTER,
                    handler: function() {
                        authDialog.hide();
                        authForm.getForm().getEl().dom.submit();
                    }
                },{
                    key: Ext.EventObject.ESC,
                    handler: function() {
                        authDialog.hide();
                    }
                }]
            });
            authForm.getForm().getEl().dom.setAttribute('action', 'mobile-proxy.php');
            authForm.getForm().getEl().dom.setAttribute('target', 'proxy-frame');
            authDialog = new Ext.Window({
                title: 'Authentication Required',
                modal: true,
                width: 320,
                closeAction: 'hide',
                layout: 'fit',
                items: [authForm]
            });
            /**
             * Bogus fix of an IE issue :-P
             */
            authDialog.show();
            authDialog.hide();
            Ext.getDom('url').focus();
        },

        /**
         * Functions
         */
        showQrCode: function() {
            var url = Ext.getDom('url').value;
            if (url) {
                Ext.DomHelper.overwrite('qrcode', {
                    tag: 'div',
                    align: 'center',
                    children: [{
                        tag: 'img',
                        src: 'qr_img.php?' + Ext.urlEncode({d: url})
                    }]
                });
                qrCodeDialog.show(this);
            }
        },
        showAuthDialog: function(url, realm) {
            Ext.getDom('auth-form-url').value = url;
            Ext.getDom('auth-form-realm').value = realm;
            authDialog.show(this);
        },
        update: function() {
            if (Ext.getDom('url').value || Ext.getDom('auth-form-url').value) {
                historiesStore.load();
                responseHeadersStore.load();
                Ext.Ajax.request({
                    url: 'response-url.php',
                    scriptTag: false,
                    success: function(xhr) {
                        /**
                         * Override only if the value is available.
                         */
                        if (xhr.responseText) {
                            Ext.getDom('url').value = xhr.responseText;
                        }
                    }
                });
                Ext.Ajax.request({
                    url: 'response-body.php',
                    scriptTag: false,
                    success: function(xhr) {
                        /**
                         * Always override.
                         */
                        Ext.DomHelper.overwrite(
                            'response-body',
                            xhr.responseText
                        );
                    }
                });
            }
        }
    };
}();
Ext.onReady(MobileSimulator.init, MobileSimulator, true);
